package com.huoyun.pay.action;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.huoyun.base.action.BaseAction;
import com.huoyun.pay.bean.BankCard;
import com.huoyun.pay.service.BankCardService;
import com.huoyun.user.bean.User;
import com.opensymphony.xwork2.ActionContext;

public class BankCardAction extends BaseAction{
	List<BankCard> bankCardList;
	BankCard bankCard;
	BankCardService bankCardService;
	
	public String saveBankCard(){
		User user = (User)getSession().getAttribute("loginUser");
		bankCard.setUserId(user.getId());
		bankCardService.saveBankCard(bankCard);
		return SUCCESS;
	}
	
	public String queryBankCards() {
		bankCardList = bankCardService.queryBankCardsByUserId(getLoginUser().getId());
		return SUCCESS;
	}
	
	public String preAddBankCard() {
		return SUCCESS;
	}
	
	public String addBankCard() {
		bankCard.setUserId(getLoginUser().getId());
		bankCard.setStatus(0);
		bankCard.setIsDefault(0);
		bankCardService.saveBankCard(bankCard);
		return SUCCESS;
	}
	
	/**
	 * 验证银行卡号是否已存在
	 * @return
	 * @throws IOException
	 */
	public String checkBankCard() throws IOException
	{
		this.setResultMsg("true");
		
		List<BankCard> bankCards = bankCardService.queryBankCardsByUserId(getLoginUser().getId());
		for (BankCard card : bankCards) {
			if (card.getCardNumber().equals(bankCard.getCardNumber())) {
				this.setResultMsg("false");
			}
		}	
		
		HttpServletResponse response = (HttpServletResponse)ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE);
		
		try
		{
			response.getWriter().print(this.getResultMsg());
		}catch (IOException e) {
			//log.error("校验密码输出流发生错误！原因：" + e.fillInStackTrace());
			
			throw e;
		}
		return null;	
	}
	
	public String preEditBankCard() {
		HttpServletRequest request = (HttpServletRequest)ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		long id = Long.valueOf(request.getParameter("id"));
		bankCard = bankCardService.getBankCardById(id);
		return SUCCESS;
	}
	
	public BankCard getBankCard() {
		return bankCard;
	}
	public void setBankCard(BankCard bankCard) {
		this.bankCard = bankCard;
	}
	public BankCardService getBankCardService() {
		return bankCardService;
	}
	public void setBankCardService(BankCardService bankCardService) {
		this.bankCardService = bankCardService;
	}

	public List<BankCard> getBankCardList() {
		return bankCardList;
	}

	public void setBankCardList(List<BankCard> bankCardList) {
		this.bankCardList = bankCardList;
	}

}
